package com.lzc.springPart;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * bean的执行流程
 */
public class BeanProcessImpl  {


    public static void main(String[] args) {

        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Config.class).setScope("singleton").getBeanDefinition();

        beanFactory.registerBeanDefinition("config",beanDefinition);

        beanFactory.addBeanPostProcessor(new MyBeanPostProcess());

        beanFactory.getBean(Config.class);

    }

    @Configuration
    static class Config implements InitializingBean , BeanNameAware {
        public Config(){
            System.out.println("构造方法");
        }

        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("初始化");
        }

        @Override
        public void setBeanName(String s) {
            System.out.println("bean name is : " + s);
        }
    }


    static class MyBeanPostProcess implements InstantiationAwareBeanPostProcessor{

        @Override // 构造方法执行前
        public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
            System.out.println("构造方法执行前");
            return null;
        }

        @Override // 构造方法执行后
        public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
            System.out.println("构造方法执行后");
            return true;
        }

        @Override // 依赖注入
        public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
            System.out.println("依赖注入");
            return pvs;
        }

        @Override // 初始化前
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("初始化前");
            return bean;
        }

        @Override // 初始化后
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            System.out.println("初始化后");
            return bean;
        }
    }

}
